/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.saber.certificacao.beansjsf.administracao;

import br.com.saber.certificacao.beansjsf.interfacebean.BeanJSFInterface;
import br.com.saber.certificacao.beansjsf.login.LoginManager;
import br.com.saber.certificacao.beansjsf.semescopo.SelectItemManager;
import br.com.saber.certificacao.ejbs.stateless.interfaces.CertificacaoBeanLocal;
import br.com.saber.certificacao.ejbs.stateless.interfaces.ProfessorVersaoBeanLocal;
import br.com.saber.certificacao.ejbs.stateless.interfaces.UsuarioBeanLocal;
import br.com.saber.certificacao.enums.Papeis;
import br.com.saber.certificacao.modelos.Certificacao;
import br.com.saber.certificacao.modelos.Usuario;
import br.com.saber.certificacao.modelos.Versao;
import br.com.saber.certificacao.modelos.relacionamentos.ProfessorVersao;
import br.com.saber.certificacao.modelos.validadores.exceptions.generica.ValidacaoExcecao;
import br.com.saber.certificacao.observador.ControleObserver;
import br.com.saber.certificacao.utils.UtilMetodos;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author Guilherme
 */
@ManagedBean(name = "professorVersaoManagerManager")
@ViewScoped
public class ProfessorVersaoManager implements BeanJSFInterface, Observer {

    @EJB
    private ProfessorVersaoBeanLocal professorVersaoBean;
    @EJB
    private CertificacaoBeanLocal certificacaoBean;
    @EJB
    private UsuarioBeanLocal usuarioBean;
    private List<Usuario> modelUsuarios;
    private List<Versao> versoesUsuario;
    private Usuario professor;
    @ManagedProperty("#{loginManager}")
    private LoginManager loginManager;
    @ManagedProperty("#{selectItemManager}")
    private SelectItemManager selectItemManager;

    /** Creates a new instance of ProfessorVersaoManager */
    public ProfessorVersaoManager() {
    }

    //====================
    // Iniciadores
    //====================
    @Override
    @PostConstruct
    public void init() {
        ControleObserver.addBeanObserver(loginManager.getUsuario(), this);
        clean();
        Logger.getLogger(this.getClass().getName()).log(Level.FINEST, "ProfessorVersaoManager.init() executado!");
    }

    @Override
    @PreDestroy
    public void end() {
        ControleObserver.removeBeanObserver(loginManager.getUsuario(), this);
        Logger.getLogger(this.getClass().getName()).log(Level.FINEST, "ProfessorVersaoManager.end() executado!");
    }

    //====================
    //Métodos de Negócio
    //====================
    public void salvarProfessor() {
        if (professor == null) {
            UtilMetodos.messageFactoringFull("professorCertificacaoAlteradoNOK", FacesMessage.SEVERITY_WARN, FacesContext.getCurrentInstance());
            return;
        }
        try {
            professor.setVersoesDesteProfessor(new TreeSet<ProfessorVersao>(converteVersao()));
            professorVersaoBean.salvarProfessorVersoes(professor);
            ControleObserver.notificaObservers(loginManager.getUsuario(), new String[]{ControleObserver.Eventos.CAD_USUARIO_EVENT});
            clean();
            UtilMetodos.messageFactoringFull("professorCertificacaoAlterado", FacesMessage.SEVERITY_INFO, FacesContext.getCurrentInstance());
        } catch (ValidacaoExcecao e) {
            if (!StringUtils.isBlank(e.getAtributoName())) {
                UtilMetodos.messageFactoringFull(UtilMetodos.getResourceBundle(e.getMessage(), FacesContext.getCurrentInstance()), null, e.getAtributoName(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
            } else {
                UtilMetodos.messageFactoringFull(e.getMessage(), FacesMessage.SEVERITY_ERROR, FacesContext.getCurrentInstance());
            }
        }
    }
    
    private Set<ProfessorVersao> converteVersao(){
        Set<ProfessorVersao> pv = new HashSet<ProfessorVersao>();
        for(Versao v : this.versoesUsuario){
            pv.add(new ProfessorVersao(professor, v));
        }
        return pv;
    } 

    private void converteProfessorVersao(){
        this.versoesUsuario = new ArrayList<Versao>();
        for(ProfessorVersao pv : professor.getVersoesDesteProfessor()){
            versoesUsuario.add(pv.getVersao());
        }
    }
    
    @Override
    public void update(Observable o, Object arg) {
        String[] args = (String[]) arg;
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals(ControleObserver.Eventos.CAD_USUARIO_EVENT)) {
                atualizar();
            }
        }
    }

    private void atualizar() {
        this.modelUsuarios = new ArrayList(this.usuarioBean.buscarUsuariosLimitadoAoPapel(Papeis.PROFESSOR));
    }

    public void clean() {
        professor = null;
        this.versoesUsuario = new ArrayList<Versao>();
    }
    //====================
    //Table Actions
    //====================
    //====================
    //SelectItem
    //====================

    public List<SelectItem> getVersoes() {
        if (professor != null) {
            return selectItemManager.getVersoes(new ArrayList<Certificacao>(this.certificacaoBean.loadLazyCertificacoesDoProfessor(professor)), false);
        }
        return new ArrayList<SelectItem>();
    }

    //=========================
    //Getters AND Setters
    //=========================
    public LoginManager getLoginManager() {
        return loginManager;
    }

    public void setLoginManager(LoginManager loginManager) {
        this.loginManager = loginManager;
    }

    public SelectItemManager getSelectItemManager() {
        return selectItemManager;
    }

    public void setSelectItemManager(SelectItemManager selectItemManager) {
        this.selectItemManager = selectItemManager;
    }

    public List<Usuario> getModelUsuarios() {
        if (modelUsuarios == null) {
            atualizar();
        }
        return modelUsuarios;
    }

    public void setModelUsuarios(List<Usuario> modelUsuarios) {
        this.modelUsuarios = modelUsuarios;
    }

    public Usuario getProfessor() {
        return professor;
    }

    public void setProfessor(Usuario professor) {
        this.professor = this.professorVersaoBean.carregarProfessorVersao(professor);
        converteProfessorVersao();
    }

    public List<Versao> getVersoesUsuario() {
        return this.versoesUsuario;
    }

    public void setVersoesUsuario(List<Versao> versoesUsuario) {
        this.versoesUsuario = versoesUsuario;
        
    }
}
